// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Linq.Expressions;
using Antlr4.Runtime.Tree;
using Microsoft.Extensions.DependencyInjection;

namespace SnapObjects.Expressions
{
    internal class EvaluateNewExpressionVisitor<TContext> : NewExpressionVisitor<EvaluateResult, TContext>
        where TContext : IParseTree
    {
        public EvaluateNewExpressionVisitor(IServiceProvider services) : base(services)
        {
        }

        public override EvaluateResult Visit(
            IExpressionVisitor<EvaluateResult> treeVisitor, TContext context, ParserOptions<EvaluateResult> options)
        {
            var expressionPolicyProvider = _services.GetService<IPolicyProvider<Expression>>();
            var expressionTreeVisitor = _services.GetService<IExpressionVisitor<Expression>>();

            if (expressionTreeVisitor == null || expressionPolicyProvider == null)
            {
                throw new NotImplementedException(Resources.NEWEXPRESSIONERROR);
            }

            var newOptions = _provider.NestParser.CreateOptions(options);

            var expressionNewVisitor = new NewExpressionVisitor<TContext>(
                expressionPolicyProvider, expressionTreeVisitor);

            var expression = expressionNewVisitor.Visit(context, newOptions);

            return _provider.NestParser.Invoke(options, expression, newOptions);
        }
    }
}
